/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Global Trust Authority is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

use plugin_manager::PluginError;

#[derive(Debug)]
pub struct AscendNpuConfig {
    pub attester_type: String,
    pub enable_boot_measurements: bool,
    pub enable_runtime_measurements: bool,
    pub ascend_sdk_path: String
}

pub const ASCEND_NPU_TCG_EVENT_LOG: &str = "TcgEventLog";
pub const ASCEND_NPU_IMA_LOG: &str = "ImaLog";

impl AscendNpuConfig {
    /// # from_json
    /// 
    /// Creates a new `AscendNpuConfig` instance from a JSON string.
    /// 
    /// # Parameters
    /// - `attester_type`: The type of the attester.
    /// - `config_json`: The JSON string containing the configuration.
    /// 
    /// # Errors
    /// 
    /// This function will return an error if:
    /// - The JSON string cannot be parsed.
    /// - Required fields are missing or have invalid types.
    /// 
    /// # Returns
    /// A `Result` containing the `AscendNpuConfig` instance or a `PluginError`.
    pub fn from_json(attester_type: String, config_json: &str) -> Result<Self, PluginError> {
        let config: serde_json::Value = serde_json::from_str(config_json)
            .map_err(|e| PluginError::InternalError(format!("Failed to parse plugin configuration as JSON: {}", e)))?;
        
        let enable_boot_measurements = config
            .get("enable_boot_measurements")
            .and_then(|v| v.as_bool())
            .unwrap_or_default();
        let enable_runtime_measurements = config
            .get("enable_runtime_measurements")
            .and_then(|v| v.as_bool())
            .unwrap_or_default();
        let ascend_sdk_path = config
            .get("ascend_sdk_path")
            .and_then(|v| v.as_str().map(String::from))
            .unwrap_or_default();

        Ok(Self {
            attester_type,
            enable_boot_measurements,
            enable_runtime_measurements,
            ascend_sdk_path,
        })
    }
}